package program;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;

import kernel.FileManager;
import kernel.exception.OSException;
import kernel.process.AbstractProcess;
import kernel.process.AbstractProcessHeader;

/**
 * Cat process.
 * For more see man() method.
 * @author Jaromir Lepic, Petr Hajek, Veronika Vencurikova
 *
 */
public class Cat extends AbstractProcess {
	
	private BufferedReader reader;
	private Queue<BufferedReader> readers = new LinkedList<BufferedReader>();
	private String inputTemp;
	
	public Cat(AbstractProcessHeader header, long pid) {
		super(header, pid);
	}

	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public String doJob(String input) throws OSException {
			
		this.inputTemp = input;
				
		for (int i = 0; i < this.params.size(); i++) {
			readers.add(FileManager.openReader(absPath(this.params.get(i), shellID)));
		}
		
		reader = readers.poll();
		return  "";
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void kill() throws OSException {
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean needParams() {
		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String continueJob() throws OSException {
		try {
			StringBuilder readBuffer = new StringBuilder("");
			String read;
			boolean end = false;
			if (reader != null) {
				for (int i = 0; i < 100; i++) {
					if ((read = reader.readLine()) == null) {
						end = true;
						break;
					}
					else {
						readBuffer.append(read + "\n");
					}
				}
			}
			else {
				end = true;
			}
			if (end) {
				if (reader != null) reader.close();
				if (!readers.isEmpty()){
					reader = readers.poll();
					return readBuffer.toString() + inputTemp;
				}
				this.shouldEnd = true;
				return readBuffer.toString() + inputTemp;
			}
			else {
				return readBuffer.toString() + inputTemp;
			}
		} catch (IOException e) {
			throw new OSException(OSException.ERR_READING);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected String finalizeJob() throws OSException {
		if (!readers.isEmpty()){
			for (BufferedReader reader: readers){
				try {
					reader.close();
				} catch (IOException e) {
				}
			}
		}
		return null;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public String man(String command) {
		String man = "";
		
		man += "    connects files and prints on standard output\n";
		man += "\n";
		man += "Command syntax:\n";
		man += "    "+command+" [FILE] ...\n";
		man += "\n";
		man += "Examples:\n";
		man += "    "+command+" file1.txt file2.txt\n";
		
		return man;
	}
}
